<?php

declare(strict_types=1);

namespace app\api\controller\customer;

use app\api\controller\Api;
use app\common\customer\logic\CustomerTagLogic;
use app\common\customer\model\Customer;
use app\common\customer\model\CustomerAllocate;
use app\common\customer\model\CustomerAllocateTag;
use app\common\customer\model\CustomerBanquet;
use app\common\customer\model\CustomerContact;
use app\common\customer\model\CustomerFavorite;
use app\common\customer\model\CustomerSource;
use app\common\customer\model\CustomerTag;
use app\common\customer\model\CustomerVisit;
use app\common\customer\validate\CustomerAppendValidate;
use app\common\customer\validate\CustomerCombineValidate;
use app\common\customer\validate\CustomerContactValidate;
use app\common\customer\validate\CustomerProductValidate;
use app\common\customer\validate\CustomerValidate;
use app\common\system\logic\FormLogic;
use app\common\system\logic\UserLogic;
use think\console\command\make\Model;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use util\Format;

// 推广部，录入客资者
class Member extends Api
{
    public function index()
    {
        $post = $this->request->post();
        $where = [];
        if (isset($post['category_id']) && !empty($post['category_id'])) $where[] = ['category_id', 'in', $post['category_id']];
        if (isset($post['status']) && !empty($post['status'])) $where[] = ['status', 'in', $post['status']];
        if (isset($post['source_id']) && !empty($post['source_id'])) $where[] = ['source_id', '=', $post['source_id']];
        if (isset($post['create_id']) && !empty($post['create_id'])) $where[] = ['create_id', '=', $post['create_id']];
        if (isset($post['date_range']) && !empty($post['date_range'])) $where[] = ['date_range', 'between', $post['date_range']];

        $model = new Customer();
        list($cfg) = Format::pagination($post);
        $model = $model->where($where);
        $userLogic = new UserLogic();
        $user = $userLogic->getUser($this->request->user['id']);
        // 管理者
        if ($user['user_type'] == 1) {
        }
        if (isset($post['keyword']) && !empty($post['keyword'])) {
            $contactType = $post['contact_type'] ?? 1;
            $keyword = $post['keyword'];
            $model = $model->whereIn('id', function ($query) use ($keyword, $contactType) {
                if ($contactType == 1) {
                    if (strlen($keyword) == 11) {
                        $query->table('tk_member_contact')->where('contact_type', 1)->where('contact', $keyword)->field('member_id');
                    } else {
                        $query->table('tk_member_contact')->where('contact_type', 1)->whereLike('contact', "%{$keyword}")->field('member_id');
                    }
                } else {
                    $query->table('tk_member_contact')->where('contact', $keyword)->field('member_id');
                }
            });
        }

        $pg = $model->order('id desc')->paginate($cfg);
        $rows = $pg->getCollection();
        foreach ($rows as $row) {
            $row->append(['source', 'creator', 'contact', 'visit_status', 'allocate', 'category']);
        }

        // 返回接口数据
        $result['list'] = $rows;
        $result['keyword'] = $post['keyword'];
        $result['pagination'] = Format::pgResult($pg);

        return success($result, '获取数据成功');
    }

    // 季总接口
    public function add()
    {
        $post = $this->request->post();
        $validate = new CustomerAppendValidate();
        if (!$validate->check($post)) return error([], $validate->getError());
        
        $user = $this->request->user;
        $customerModel = new Customer();
        $customerModel->startTrans();
        $customerData = [];
        // 生成客资编号
        $customerData['member_no'] = $customerModel->generateMemberNo();
        $customerData['fullname'] = $post['fullname'];
        $customerData['sex'] = $post['sex'];
        $customerData['source_id'] = $post['source_id'];
        $customerData['remark'] = $post['remark'];
        $customerData['create_id'] = $user['id'];
        $customerData['operator_id'] = $user['id'];
        $customerData['category_id'] = 1; // 默认婚宴婚庆类
        $customerData['province_id'] = 802;
        $customerData['city_id'] = 802;
        try {
            $customerModel->save($customerData);
            $memberId = $customerModel->id;
        } catch (DbException $e) {
            $customerModel->rollback();
            return error([], $e->getMessage());
        }

        // 创建联系方式
        $contactModel = new CustomerContact();
        $contactData = [];
        if (!empty($post['mobile'])) {
            $contactDataItem = [];
            $contactDataItem['member_id'] = $memberId;
            $contactDataItem['contact_type'] = 1;
            $contactDataItem['contact'] = $post['mobile'];
            $contactDataItem['operator_id'] = $user['id'];
            $contactDataItem['create_time'] = time();
            array_push($contactData, $contactDataItem);
        }

        if (!empty($post['wechat'])) {
            $contactDataItem = [];
            $contactDataItem['member_id'] = $memberId;
            $contactDataItem['contact_type'] = 2;
            $contactDataItem['contact'] = $post['wechat'];
            $contactDataItem['operator_id'] = $user['id'];
            $contactDataItem['create_time'] = time();
            array_push($contactData, $contactDataItem);
        }

        if (!empty($post['telephone'])) {
            $contactDataItem = [];
            $contactDataItem['member_id'] = $memberId;
            $contactDataItem['contact_type'] = 3;
            $contactDataItem['contact'] = $post['telephone'];
            $contactDataItem['operator_id'] = $user['id'];
            $contactDataItem['create_time'] = time();
            array_push($contactData, $contactDataItem);
        }

        try {
            $contactModel->saveAll($contactData);
        } catch (DbException $e) {
            $customerModel->rollback();
            return error([], $e->getMessage());
        }

        // 添加意向产品
        $productModel = new CustomerBanquet();
        $productData = [];
        $productData['member_id'] = $memberId;
        $productData['category_id'] = 1;
        $productData['create_id'] = $user['id'];
        $productData['operator_id'] = $user['id'];
        $productData['remark'] = $post['remark'];
        $productData['budget'] = $post['budget'];
        $productData['table_amount'] = $post['table_amount'];
        $productData['event_date'] = $post['event_date'];
        $productData['zone'] = $post['zone'];
        try {
            $productModel->save($productData);
        } catch (DbException $e) {
            $customerModel->rollback();
            return error([], $e->getMessage());
        }

        // 添加分配
        $allocateModel = new CustomerAllocate();
        $allocateData = [];
        $allocateData['member_id'] = $memberId;
        $allocateData['create_id'] = $user['id'];
        $allocateData['from_user_id'] = $user['id'];
        $allocateData['user_id'] = $user['id'];
        $allocateData['assign_type'] = 1; // 分配方式添加获取
        $allocateData['assign_status'] = 0; // 分配状态
        try {
            $allocateModel->save($allocateData);
        } catch (DbException $e) {
            $customerModel->rollback();
            return error([], $e->getMessage());
        }

        // 添加成功
        $customerModel->commit();
        return success([], "客资录入成功");
    }

    // 客服的客资
    public function create()
    {
        $post = $this->request->post();

        // 检测提交的客资基本信息
        $validate1 = new CustomerValidate();
        if (!$validate1->scene('create')->check($post)) return error([], $validate1->getError());

        // 检测提交的联系方式信息
        if (!is_array($post['contacts'])) return error([], '联系方式是数据错误');
        $validate2 = new CustomerContactValidate();
        foreach ($post['contacts'] as $row) {
            if (!$validate2->scene('create')->check($row)) {
                return error([], $row['contact'] . $validate2->getError());
            }
        }

        // 验证是否提交意向产品
        if (!is_array($post['product'])) return error([], "意向产品数据错误");
        $validate3 = new CustomerProductValidate();
        if (!$validate3->scene('create')->check($post['product'])) {
            return error([], $validate3->getError());
        }

        $product = $post['product'];

        // 创建基本信息
        $user = $this->request->user;
        $customerModel = new Customer();
        $customerModel->startTrans();
        $post['visit_times'] = 0;
        $post['create_id'] = $user['id']; // 创建者
        $post['operator_id'] = $user['id']; // 操作者
        $post['category_id'] = $product['category_id'];

        try {
            $customerModel->save($post);
        } catch (DbException $e) {
            $customerModel->rollback();
            return error([], '创建客资失败');
        }

        // 检测创建客资是否成功
        if (empty($customerModel->id)) {
            $customerModel->rollback();
            return error([], "创建客资失败");
        }
        $memberId = $customerModel->id;

        // 创建联系方式
        $data = [];
        foreach ($post['contacts'] as $row) {
            $row['operator_id'] = $user['id'];
            $row['member_id'] = $memberId;
            $row['create_time'] = time();
            array_push($data, $row);
        }
        try {
            $contactModel = new CustomerContact();
            $contactModel->insertAll($data);
        } catch (DbException $e) {
            $customerModel->rollback();
            return error([], "联系方式录入不正确, 客资录入失败");
        }

        // 创建分配
        $data = [];
        $data['visit_times'] = 0;
        $data['member_id'] = $memberId;
        $data['create_id'] = $user['id'];
        $data['from_user_id'] = $user['id'];
        $data['user_id'] = $user['id'];
        $data['assign_type'] = 1; // 分配方式添加获取
        $data['assign_status'] = 0; // 分配状态
        try {
            $allocateModel = new CustomerAllocate();
            $allocateModel->save($data);
        } catch (DbException $e) {
            $customerModel->rollback();
            return error([], "创建分配失败,客资创建失败");
        }

        $productModel = new CustomerBanquet();
        $product['create_id'] = $user['id'];
        $product['member_id'] = $memberId;
        try {
            $productModel->save($product);
        } catch (DbException $e) {
            $customerModel->rollback();
            return error([], $e->getMessage());
        }

        $customerModel->commit();
        return success([], "客资录入成功");
    }

    // 读取客资信息
    public function read()
    {
        $post = $this->request->post();
        $user = $this->request->user;
        if (empty($post['member_id'])) return error([], "参数错误");
        $memberId = $post['member_id'];

        $customerModel = new Customer();
        $customer = $customerModel->where('id', $memberId)->find();
        if (empty($customer)) return error([], "客资已不存在");
        $customer->append(['creator', 'source', 'visit_status']);
        $result['member'] = $customer;

        // 获取客资的联系方式
        $contactModel = new CustomerContact();
        $contacts = $contactModel->where('member_id', $memberId)->select();
        foreach ($contacts as $contact) {
            $contact->append(['tag']);
        }
        $result['contacts'] = $contacts;

        // 获取意向产品
        $productModel = new CustomerBanquet();
        $products = $productModel->where('member_id', $memberId)->select();
        foreach ($products as $row) {
            $row->append(['creator', 'city', 'category']);
        }
        $result['products'] = $products;

        // 重复渠道
        $sourceModel = new CustomerSource();
        $sources = $sourceModel->where('member_id', $memberId)->select();
        foreach ($sources as $row) {
            $row->append(['source', 'creator']);
        }
        $result['sources'] = $sources;

        // 获取收藏信息
        $where = [];
        $where['member_id'] = $memberId;
        $where['user_id'] = $user['id'];
        $favModel = new CustomerFavorite();
        $fields = 'member_id,user_id,type';
        $result['favorites'] = $favModel->where($where)->field($fields)->select();

        return success($result, "获取数据成功");
    }

    // 保存客资的基本信息
    public function save()
    {
        $post = $this->request->post();

        // 检测提交的客资基本信息
        $validate1 = new CustomerValidate();
        if (!$validate1->scene('edit')->check($post)) return error([], $validate1->getError());

        $user = $this->request->user;
        $customerModel = new Customer();
        $customerModel->startTrans();
        $post['operator_id'] = $user['id']; // 操作者
        $row = $customerModel->where('id', $post['id'])->find();
        if (empty($row)) return error([], "客资已经不存在");

        try {
            $row->save($post);
        } catch (DbException $e) {
            $customerModel->rollback();
            return error([], $e->getMessage());
        }
        $customerModel->commit();

        // 核销表单token
        if (!empty($post['form_token'])) {
            $formLogic = new FormLogic();
            $formLogic->removeToken($post['form_token']);
        }
        return success([], "更新客资基本信息成功");
    }

    // 保存详细信息
    public function update()
    {
        $post = $this->request->post();

        // 检测提交的客资基本信息
        $validate1 = new CustomerValidate();
        if (!$validate1->scene('edit')->check($post)) return error([], $validate1->getError());

        // 验证是否提交意向产品
        if (!is_array($post['products'])) return error([], "意向产品数据错误");
        $validate3 = new CustomerProductValidate();
        foreach ($post['products'] as $row) {
            if (!$validate3->scene('create')->check($row)) {
                return error([], $validate3->getError());
            }
        }

        $user = $this->request->user;
        $customerModel = new Customer();
        $customerModel->startTrans();

        // 操作者
        $post['operator_id'] = $user['id'];
        $member = $customerModel->where('id', $post['id'])->find();
        if (empty($member)) return error([], "客资已经不存在");
        try {
            $member->save($post);
        } catch (DbException $e) {
            $customerModel->rollback();
            return error([], $e->getMessage());
        }

        $productModel = new CustomerBanquet();
        foreach ($post['products'] as $row) {
            if (empty($row['id'])) {
                $customerModel->rollback();
                return error([], "意向产品参数错误");
            }

            $product = $productModel->where('id', $row['id'])->find();
            try {
                $product->save($row);
            } catch (DbException $e) {
                $customerModel->rollback();
                return error([], $e->getMessage());
            }
        }

        $customerModel->commit();
        if (isset($post['form_token'])) {
            // 核销表单token
            $formLogic = new FormLogic();
            $formLogic->removeToken($post['form_token']);
        }
        return success([], "操作成功");
    }

    public function getMemberByContact()
    {
        $post = $this->request->post();
        if (empty($post['member_id'])) return error([], "参数错误，请刷新或者联系管理员");
        if (empty($post['keywords'])) return error([], "联系方式必须");

        $contactModel = new CustomerContact();
        try {
            $row = $contactModel->where('contact', $post['keywords'])->find();
        } catch (DataNotFoundException $e) {
            return error([], "客资不存在");
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }

        if ($row['member_id'] == $post['member_id']) return error([], "请勿合并当前客资");

        $productModel = new CustomerBanquet();
        try {
            $products = $productModel->where(['member_id' => $row->member_id])->select();
        } catch (DataNotFoundException $e) {
            return error([], "不存在意向数据");
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }

        foreach ($products as $product) {
            $product->append(['creator', 'city', 'category']);
        }
        $result['products'] = $products;
        $result['member_id'] = $row['member_id'];

        return success($result);
    }

    // 合并客资
    public function doCombine()
    {
        $post = $this->request->post();
        $validate = new CustomerCombineValidate();
        if (!$validate->check($post)) return error([], $validate->getError());

        $user = $this->request->user;
        $contactModel = new CustomerContact();
        try {
            $contact = $contactModel->where('contact', $post['keywords'])->find();
        } catch (DataNotFoundException $e) {
            return error([], "客资不存在");
        } catch (DbException $e) {
            return error([], $e->getMessage());
        }
        if ($contact['member_id'] == $post['member_id']) return error([], "请勿合并当前客资");

        // 删除客资
        $memberModel = new Customer();
        $memberModel->startTrans();
        try {
            $member = $memberModel->where('id', $contact['member_id'])->find();
            $remark = $member->remark;
        } catch (DataNotFoundException $e) {
            $memberModel->rollback();
            return error([], "客资已经不存在");
        } catch (DbException $e) {
            $memberModel->rollback();
            return error([], $e->getMessage());
        }

        try {
            $member->delete();
        } catch (\Exception $e) {
            $memberModel->rollback();
            return error([], $e->getMessage());
        }

        // 替换联系方式
        try {
            $rows = $contactModel->where('member_id', $contact['member_id'])->select();
            foreach ($rows as $row) {
                try {
                    $row->save(['member_id' => $post['member_id']]);
                } catch (DbException $e) {
                    $row->delete();
                }
            }
        } catch (DataNotFoundException $e) {
        } catch (DbException $e) {
        }

        // 替换分配记录
        $allocateModel = new CustomerAllocate();
        $allocates = $allocateModel->where('member_id', $contact['member_id'])->select();
        $userIds = $allocateModel->where('member_id', $post['member_id'])->column('user_id');
        foreach ($allocates as $allocate) {
            if (in_array($allocate['user_id'], $userIds)) {
                $allocate->delete();
            } else {
                $allocate->save(['member_id' => $post['member_id']]);
            }
        }

        // 替换跟进记录
        CustomerVisit::update([
            'member_id' => $post['member_id']
        ], [
            'member_id' => $contact['member_id']
        ]);

        $categoryTypeId = 0;
        $banquetModel = new CustomerBanquet();
        if ($post['product_member_id'] == $post['member_id']) {
            // 保留当前客资信息，删除要替换的客资
            try {
                $banquet = $banquetModel->where('member_id', $contact['member_id'])->find();
                $banquet->delete();
            } catch (DataNotFoundException $e) {
            } catch (DbException $e) {
            }
        } else {
            try {
                $banquet = $banquetModel->where('member_id', $post['member_id'])->find();
                $banquet->delete();
            } catch (DataNotFoundException $e) {
            } catch (DbException $e) {
            }

            try {
                $banquet = $banquetModel->where('member_id', $contact['member_id'])->find();
                $categoryTypeId = $banquet['category_id'];
                $banquet->save(['member_id' => $post['member_id']]);
            } catch (DataNotFoundException $e) {
            } catch (DbException $e) {
            }
        }

        $currentMember = $memberModel->where('id', $post['member_id'])->find();
        $newRemark = $currentMember['remark'] . "\n" . $remark;
        $updateMemberData = [];
        if ($categoryTypeId > 0) $updateMemberData['category_id'] = $categoryTypeId;
        $updateMemberData['remark'] = $newRemark;
        $currentMember->save();

        $hasWhere = [];
        $hasWhere[] = ['member_id', '=', $contact['member_id']];
        \app\common\order\model\Order::update(['member_id' => $post['member_id']], $hasWhere);

        $memberModel->commit();

        // 记录日志
        return success([], "合并成功");
    }

    // 更新基本信息 (季总)
    public function edit()
    {
        $allocateId = $this->request->param('allocate_id');
        $memberId = $this->request->param('member_id');
        $user = $this->request->user;
        $allocateModel = new CustomerAllocate();
        $allocate = $allocateModel->where('id', $allocateId)->where('user_id', $user['id'])->find();
        if (empty($allocate)) return error([], "无权限");
        if ($allocate['member_id'] != $memberId) return error([], "客资不匹配");

        $model = new Customer();
        $model->startTrans();
        $row = $model->where('id', $memberId)->find();
        $post = $this->request->post();
        try {
            $data = [];
            $data['fullname'] = $post['fullname'];
            $data['sex'] = $post['sex'];
            $data['remark'] = $post['remark'];
            $row->save($data);
            $model->commit();
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        return success([], "更新成功");
    }
}
